//
//  SetViewController.m
//  ShangAPP
//
//  Created by macpro on 16/1/21.
//  Copyright © 2016年 wangdao. All rights reserved.
//
//15665775172

#import "SetViewController.h"
#import "MyTools.h"
#import "SetTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "MoneyViewController.h"
#import "IdeaViewController.h"
#import "ViewController.h"
#import "TodayBusiViewController.h"
#import "NewsViewController.h"
#import "JPUSHService.h"


@interface SetViewController ()
<UITableViewDataSource,
UITableViewDelegate,
UIAlertViewDelegate>{
    
    UITableView *_myTab;
    
    UIImageView  *_heardeImage;
    UILabel      *_namelab;
    UILabel      *_phonelab;
    UILabel      *_cardlab;
    
    NSArray      *_titlearr;
    NSArray      *_imagearr;
    
    NSDictionary *_myDic;
    
    UIImageView  *_dianImage;
}

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:20],
       NSForegroundColorAttributeName:UIColorFromRGB(0x444444)}];
    
    //nav底部线消失
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBarTintColor:UIColorFromRGB(MYColor)];
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-xiaoxi"] style:UIBarButtonItemStylePlain target:self action:@selector(getMessage)];
//    [self.navigationItem.rightBarButtonItem setTintColor:UIColorFromRGB(0x444444)];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate =(id)self;
    
    [self viewCreate];
}

-(void)getDate{
    NSString *url = @"http://www.xsy777.com/app/user/uidlist.html";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"]};
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:url parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            _myDic = [[NSDictionary alloc]initWithDictionary:[[responseObject objectForKey:@"data"] firstObject]];
            
            [_heardeImage sd_setImageWithURL:[NSURL URLWithString:[_myDic objectForKey:@"avatar128"]]];
            _namelab.text = [NSString stringWithFormat:@"%@",[_myDic objectForKey:@"nickname"]];
            _phonelab.text = [NSString stringWithFormat:@"%@",[_myDic objectForKey:@"mobile"]];
            _cardlab.text = [NSString stringWithFormat:@"%@",[_myDic objectForKey:@"address"]];
            [_myTab reloadData];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}



-(void)viewCreate{
    UIView *headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 100 * MYHEIGHT+10)];
    headview.backgroundColor = UIColorFromRGB(MYColor);
    [self.view addSubview:headview];
    
    //NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    _heardeImage = [[UIImageView alloc]initWithFrame:CGRectMake(30 * MYWIDTH, 14.5 * MYWIDTH, 71 * MYWIDTH, 71 * MYWIDTH)];
    _heardeImage.layer.cornerRadius = 35.5 * MYWIDTH;
    _heardeImage.layer.masksToBounds = YES;
    _heardeImage.userInteractionEnabled = YES;
    
    //_heardeImage.image = [UIImage imageNamed:@"touxiang"];
    [headview addSubview:_heardeImage];
    
    
    _namelab = [[UILabel alloc]initWithFrame:CGRectMake(116 * MYWIDTH, 37.5 * MYWIDTH, WIDTH - 150 * MYWIDTH, 20 * MYWIDTH)];
    
    _namelab.textColor = UIColorFromRGB(0x444444);
    _namelab.font = [UIFont systemFontOfSize:15];
    [headview addSubview:_namelab];
    
//    UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake(116 * MYWIDTH, 62 * MYWIDTH, 18 * MYWIDTH, 18 * MYWIDTH)];
//    image1.image = [UIImage imageNamed:@"iconfont-dianhua"];
//    [headview addSubview:image1];
    
    _phonelab = [[UILabel alloc]initWithFrame:CGRectMake(116 * MYWIDTH, 63 * MYWIDTH, WIDTH - 150 * MYWIDTH, 20 * MYWIDTH)];
    
    _phonelab.font = [UIFont systemFontOfSize:13];
    _phonelab.textColor = UIColorFromRGB(0x444444);
    [headview addSubview:_phonelab];
    
    
//    UIImageView *image2 = [[UIImageView alloc]initWithFrame:CGRectMake(116 * MYWIDTH, 66 * MYWIDTH, 18 * MYWIDTH, 18 * MYWIDTH)];
//    image2.image = [UIImage imageNamed:@"iconfont-xinyongqia"];
//    [headview addSubview:image2];
//    
//    _cardlab = [[UILabel alloc]initWithFrame:CGRectMake(140 * MYWIDTH, 68 * MYWIDTH, WIDTH - 150 * MYWIDTH, 20 * MYWIDTH)];
//    
//    _cardlab.font = [UIFont systemFontOfSize:13];
//    _cardlab.textColor = UIColorFromRGB(0x444444);
//    [headview addSubview:_cardlab];
    
    
    _myTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 108)];
    _myTab.rowHeight = 50;
    _myTab.backgroundColor = UIColorFromRGB(0xefeff1);
    _myTab.tableHeaderView = headview;
    _myTab.scrollEnabled = NO;
    _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myTab.showsVerticalScrollIndicator = NO;
    //_myTab.tableHeaderView = headview;
    _myTab.delegate = self;
    _myTab.dataSource = self;
    [self.view addSubview:_myTab];
    _titlearr = [[NSArray alloc]initWithObjects:@"我的钱包",@"有效订单",@"消息中心",@"意见反馈", nil];
    _imagearr = [[NSArray alloc]initWithObjects:@"我的钱包",@"有效订单",@"消息中心",@"意见反馈", nil];
    
    //[_myTab reloadData];
}

#pragma mark tableview代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }else if (section == 1){
        return 1;
    }else if (section == 2){
        return 1;
    }
    return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    SetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[SetTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        if (indexPath.section == 2) {
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
            [btn setTitle:@"注销登录" forState:UIControlStateNormal];
            [btn setTitleColor:UIColorFromRGB(0xfa3f1e) forState:UIControlStateNormal];
            btn.backgroundColor = [UIColor clearColor];
            btn.titleLabel.font = [UIFont systemFontOfSize:18];
            [btn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:btn];
            cell.myview.backgroundColor =[UIColor clearColor];
        }
    }
    
    if (indexPath.section == 0) {
        cell.myImage.image = [UIImage imageNamed:[_imagearr objectAtIndex:indexPath.row]];
//        cell.myLabel.text = [_titlearr objectAtIndex:indexPath.row];
        cell.myLabel.text =[NSString stringWithFormat:@"%@",[_titlearr objectAtIndex:indexPath.row]];
        if (indexPath.row == 2) {
            cell.myview.backgroundColor =[UIColor clearColor];
            NSUserDefaults * user =[NSUserDefaults standardUserDefaults];
// 消息  -  红点
            if ([[user objectForKey:@"xiaoxi"] isEqualToString:@"xiaoxi"]) {
                NSLog(@"%@",[user objectForKey:@"xiaoxi"]);
                _dianImage =[[UIImageView alloc]initWithFrame:CGRectMake(60 * MYWIDTH+60, 5, 6, 6)];
                _dianImage.backgroundColor =[UIColor redColor];
                _dianImage.layer.cornerRadius =3;
                _dianImage.layer.masksToBounds =YES;
                [cell addSubview:_dianImage];
            }
            
        }
    }else if (indexPath.section == 1){
        cell.myImage.image = [UIImage imageNamed:[_imagearr objectAtIndex:indexPath.row + 3]];
//        cell.myLabel.text = [_titlearr objectAtIndex:indexPath.row + 3];
        cell.myLabel.text =[NSString stringWithFormat:@"%@",[_titlearr objectAtIndex:indexPath.row + 3]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.row == 0) {
            cell.myview.backgroundColor =[UIColor clearColor];
        }
    }
    return cell;
}
// 设置每组头部视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 10;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
//        if (indexPath.row == 0) {
//            SetUpViewController *setup = [[SetUpViewController alloc]init];
//            [self.navigationController pushViewController:setup animated:YES];
//        }else
            if (indexPath.row == 0){
            MoneyViewController *money = [[MoneyViewController alloc]init];
            [self.navigationController pushViewController:money animated:YES];
        }else if (indexPath.row == 1){
            TodayBusiViewController *today = [[TodayBusiViewController alloc]init];
            [self.navigationController pushViewController:today animated:YES];
        }else if (indexPath.row == 2){
            
            NewsViewController * newsVC =[[NewsViewController alloc]init];
            [self.navigationController pushViewController:newsVC animated:YES];
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
//            ContactViewController *contact = [[ContactViewController alloc]init];
//            [self.navigationController pushViewController:contact animated:YES];
            IdeaViewController *idea = [[IdeaViewController alloc]init];
            [self.navigationController pushViewController:idea animated:YES];
        }else if (indexPath.row == 1){
            IdeaViewController *idea = [[IdeaViewController alloc]init];
            [self.navigationController pushViewController:idea animated:YES];
        }
    }
    
}

-(void)cancel{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"注销登录" message:nil delegate:self cancelButtonTitle:@"再看看" otherButtonTitles:@"注销", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        
    }else if (buttonIndex == 1){
        
        [self cancelLogin];
    }
}

-(void)cancelLogin{
    NSString *url = @"http://www.xsy777.com/app/user/logout.html";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"]};
    
    AFHTTPRequestOperationManager *mannager = [MyTools initAFHttpManager];
    
    [mannager POST:url parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            [self.view makeToast:@"注销成功" duration:1.0 position:CSToastPositionCenter];
            [user setObject:@"" forKey:@"coordinate"];
            [user setObject:@"" forKey:@"city"];
            [user setObject:@"" forKey:@"token"];
            [self cancelJpush];
            [user synchronize];
            
            ViewController *view = [[ViewController alloc]init];
//            [self.navigationController pushViewController:view animated:YES];
            [self.navigationController presentViewController:view animated:YES completion:nil];
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}
#pragma mark Jpush消除标签、别名
-(void)cancelJpush{
    [JPUSHService setTags:nil alias:@"" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags , iAlias);
    }];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   [self viewCreate];
    [self getDate];
    
    //[_myTab reloadData];
}



@end
